package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.net.aso.e;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.ReaderDAO;
import mwa.cs.dao.RouteDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Route;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS12002Srvl
 */
public class CS12002Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
    private Database db ;
    private String vaAgentBrowser;
    private String vaUrlAddress;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS12002Srvl() {
        super();
    }
    
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    String vaProcessType = request.getParameter("process_type");
	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
	vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    vaUrlAddress = request.getParameter("url_address");
    vaAgentBrowser = request.getParameter("agent_browser");
		if(vaProcessType.equals("insert")){ 
			insert(request,response);	
		} else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else if(vaProcessType.equals("getReaderName")){
			getReaderName(request,response);
		}else{
			getDataTable(request,response);
		}
	
    }
    public void delete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		int  vnZoneId = Integer.parseInt(request.getParameter("zoneid"));
		int  vnRouteId = Integer.parseInt(request.getParameter("routeid"));
		RouteDAO voRouteDAO = new RouteDAO(db);
		try {
			db.beginTransaction();
			voRouteDAO.deleteRouteBySiteId(vnSiteId, vnZoneId, vnRouteId);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS12002", JDate.getDate(), JDate.getTime(),vnUserId, "CS12002Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally{
			db.close();
		}
		response.getWriter();
    }
    
    public void update(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		int vnZoneId = Integer.parseInt(request.getParameter("zone"));
		int vnRouteId =Integer.parseInt(request.getParameter("route"));
		String vaDesp = request.getParameter("desp");
		int vnOldRouteId = Integer.parseInt(request.getParameter("oldRouteID"));
		int vnOldZoneId = Integer.parseInt(request.getParameter("oldZoneID"));
		int vnReadId = Integer.parseInt(request.getParameter("emp"));
		RouteDAO voRouteDAO = new RouteDAO(db);
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		
		Route poRoute = new Route();
		poRoute.setVnZoneId(vnZoneId);
		poRoute.setVnRouteId(vnRouteId);
		poRoute.setVaRouteDescription(vaDesp);
		poRoute.setVnReaderId(vnReadId);
		poRoute.setVnUpdateUserId(vnUserId);
		poRoute.setVaUpdateDate(vaDate);
		poRoute.setVaInsertTime(vaTime);
		try {
			db.beginTransaction();
			voRouteDAO.updateRoute(vnSiteId, vnOldZoneId, vnOldRouteId, poRoute);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS12002", JDate.getDate(), JDate.getTime(),vnUserId, "CS12002Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally{
			db.close();
		}
		response.getWriter().write("success");
    }
    
    
    public void insert(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		int vnZoneId = Integer.parseInt(request.getParameter("zone"));
		int vnRouteId = Integer.parseInt(request.getParameter("route"));
		String vaDesp = request.getParameter("desp");
		int vnReadId = Integer.parseInt(request.getParameter("emp"));
		RouteDAO voRouteDAO = new RouteDAO(db);
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		List<Map<String, Object>> volistChecked =voRouteDAO.isCheckZoneAndRoute(vnSiteId, vnZoneId, vnRouteId);
		if(volistChecked.size()==0){
			Route voRoute = new Route();
			voRoute.setVnSiteId(vnSiteId);
			voRoute.setVnZoneId(vnZoneId);
			voRoute.setVnRouteId(vnRouteId);
			voRoute.setVaRouteDescription(vaDesp);
			voRoute.setVnReaderId(vnReadId);
			voRoute.setVnInsertUserId(vnUserId);
			voRoute.setVaInsertDate(vaDate);
			voRoute.setVaInsertTime(vaTime);
			
			try {
				db.beginTransaction();
				voRouteDAO.addRoute(voRoute);
				db.commit();
			} catch (Exception  ex) {
				SMErrorLogDAO.getInstance().addLog(0, "CS12002", JDate.getDate(), JDate.getTime(),vnUserId, "CS12002Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);db.rollback();
			} finally{
				db.close();
			}
	    	response.getWriter().write("success");
	    	
		}else{
			db.close();
			response.getWriter().write("fail");
		}
			
		/*try {
			voRouteDAO.addRoute(voRoute);
			response.getWriter().write("success");
		} catch(Exception ex){
			SMErrorLogDAO.addLog(0, "CS12002", JDate.getDate(), JDate.getTime(),vnUserId, "CS12002Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);
			response.getWriter().write("fail");
		} finally{
			db.close();
		}*/
		
			
    }
    
    public void edit(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		int vnZoneId = Integer.parseInt(request.getParameter("id"));
		int vnRouteId =Integer.parseInt(request.getParameter("route"));
		String vaReader = request.getParameter("reader");
		RouteDAO voRouteDAO = new RouteDAO(db);
		ReaderDAO voReaderDAO = new ReaderDAO(db);
		JSONObject voObject = new JSONObject();
		voObject.put("zone",vnZoneId);
		voObject.put("route",vnRouteId);
		voObject.put("desp",voRouteDAO.findRouteBySiteAndRouteId(vnSiteId, vnZoneId, vnRouteId, "ROUTE_DESCRIPTION"));
		voObject.put("emp",vaReader);
		PrintWriter voOut = response.getWriter();
		db.close();
		voOut.print(voObject.toJSONString());
		
    }
    
    public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColomn = null;
		RouteDAO voRouteDAO = new RouteDAO(db);
		List<Map<String, Object>> voListFindAll ;
		voListFindAll = voRouteDAO.findRouteBySiteId(vnSiteId);
		for(int i = 0 ;i<voListFindAll.size();i++){
			Map<String, Object> mapItem = (Map<String , Object>)  voListFindAll.get(i);
			voColomn = new JSONArray();
			voColomn.add(i+1);
			voColomn.add(mapItem.get("ZONE_NAME"));
			voColomn.add(mapItem.get("ROUTE_ID"));
			voColomn.add(mapItem.get("ROUTE_DESCRIPTION"));
			voColomn.add(mapItem.get("READER_NAME"));
			voColomn.add(mapItem.get("ZONE_ID"));
			voRow.add(voColomn);
		}
		voObject.put("iTotalRecords", voListFindAll.size());
		voObject.put("iTotalDisplayRecords", voListFindAll.size());
		voObject.put("aaData", voRow);
		PrintWriter voOut = response.getWriter();
		
		db.close();
		voOut.print(voObject.toJSONString());
		
    }
    public void getReaderName(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		String vaReaderName =request.getParameter("readerName");
		String[] vaReadName = null, vaReadId = null;
		this.db = new Database();
		if(vaReaderName != null || vaReaderName.equals("yes")){
			ReaderDAO voReaderDAO =new ReaderDAO(db);
			List<Map<String,Object>>  voResult = voReaderDAO.findReaderNameAndReaderIdBySiteAndReaderId();
			vaReadName = new String[voResult.size()];
			vaReadId = new String[voResult.size()];
			for(int i=0;i<voResult.size();i++){
				Map<String,Object> voObject = voResult.get(i);
				vaReadName[i] = voObject.get("READER_NAME").toString();
				vaReadId[i] =  voObject.get("READER_ID").toString();
			}
			
			JSONObject voObject = new JSONObject();
			JSONArray voList = new JSONArray();
			PrintWriter voOut = response.getWriter();
			if (vaReadName != null) {
				for (int i = 0; i < vaReadName.length; i ++) {
					voList.add(vaReadName[i]);
				}
			}
			voObject.put("readName", voList);
			JSONArray voList2 = new JSONArray();
			if (vaReadId != null) {
				for (int i = 0; i < vaReadId.length; i ++) {
					voList2.add(vaReadId[i]);
				}
			}
			voObject.put("readId", voList2);
			
			db.close();
			voOut.print(voObject.toJSONString());
			
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

}
